﻿using AutoMapper;
using BookStores.IDomain;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using QuickFramework.SqlSugarOrm;
using BookStores.DTO.Request;
using Utility.Extensions;
using Microsoft.AspNetCore.Http;
using IdentityServer4.Extensions;

namespace BookStores.Domain
{
    /// <summary>
    /// 图书业务
    /// </summary>
    public class Books : IBooks
    {
        BookStores.Contracts.IBooksRepository m_IBooksRepository;
        BookStores.Contracts.IBookPicturesRepository m_IBookPicturesRepository;
        BookStores.Contracts.IGoodsTagRepository m_IGoodsTagRepository;
        BookStores.Contracts.IBookAuthorsRepository m_IBookAuthorsRepository;
        BookStores.Contracts.IBookLanguageRepository m_IBookLanguageRepository;

        IMapper m_IMapper;
        HttpContext m_HttpContext;
        public Books(BookStores.Contracts.IBooksRepository booksRepository
                    , BookStores.Contracts.IBookPicturesRepository bookPicturesRepository
                    , BookStores.Contracts.IGoodsTagRepository goodsTagRepository
                    , BookStores.Contracts.IBookAuthorsRepository bookAuthorsRepository
                    , BookStores.Contracts.IBookLanguageRepository bookLanguageRepository
                    , IMapper mapper
                    , IHttpContextAccessor httpContextAccessor)
        {
            m_IBooksRepository = booksRepository;
            m_IBookPicturesRepository = bookPicturesRepository;
            m_IGoodsTagRepository = goodsTagRepository;
            m_IBookAuthorsRepository = bookAuthorsRepository;
            m_IBookLanguageRepository = bookLanguageRepository;

            m_IMapper = mapper;
            m_HttpContext = httpContextAccessor.HttpContext;
        }
        /// <summary>
        /// 根据ID 获取图书信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<BookInfo> GetBookInfo(string id)
        {
            var book =await m_IBooksRepository.Queryable().InSingleAsync(id);

            var bookPictures =await m_IBookPicturesRepository.Queryable().Where(t => t.Book_ID == book.ID).OrderBy(t => t.Book_Picture_Order).ToListAsync();
            BookInfo bookInfo = m_IMapper.Map<BookInfo>(book);
            bookInfo.Book_Priture_List = bookPictures.Select(t => t.Book_Picture_Url).ToArray();
            return bookInfo;
        }


        /// <summary>
        /// 保存图书相关信息
        /// </summary>
        /// <param name="bookInfo"></param>
        /// <returns></returns>
        public async Task<(bool,string)> Save(BookInfo bookInfo)
        {
            bool isSuccess = false;
            BookStores.Entity.Books book = m_IMapper.Map<BookStores.Entity.Books>(bookInfo);
            bool isEdit = !string.IsNullOrEmpty(book.ID);
            string guid = book.ID;

            if ((bookInfo.Book_Series?.Length ?? 0) > 0)
            {
                for (int i = 0; i < bookInfo.Book_Series.Length; i++)
                {
                    bookInfo.Book_Series[i] = bookInfo.Book_Series[i].StrTrim();
                }
                book.Book_Series = string.Join(',', bookInfo.Book_Series);
                await m_IGoodsTagRepository.AddNotExists(bookInfo.Book_Series, BookStores.DTO.GoodsTagType.BookSeries);
            }
            if ((bookInfo.Book_Tag?.Length ?? 0) > 0)
            {
                for (int i = 0; i < bookInfo.Book_Tag.Length; i++)
                {
                    bookInfo.Book_Tag[i] = bookInfo.Book_Tag[i].StrTrim();
                }
                book.Book_Tag = string.Join(',', bookInfo.Book_Tag);
                await m_IGoodsTagRepository.AddNotExists(bookInfo.Book_Tag, BookStores.DTO.GoodsTagType.BookTag);
            }
            await m_IGoodsTagRepository.AddNotExists(new string[] { bookInfo.Book_Publishing }, BookStores.DTO.GoodsTagType.Publishing);

            using (IUnitOfWork unitOfWork = new UnitOfWork().CreateUoW())
            {
                if (isEdit)
                {
                    var dbBook = m_IBooksRepository.Queryable(unitOfWork);
                    await m_IBookPicturesRepository.Deleteable(unitOfWork).Where(t => t.Book_ID == book.ID).ExecuteCommandAsync();

                    book.ModifyBy = m_HttpContext.User?.GetDisplayName();
                    book.ModifyOn = book.NowSystemTime;
                }
                else
                {
                    book.ID = book.NewKey;
                    guid = book.ID;
                    book.IsActive = "Y";
                    book.CreatedBy = m_HttpContext.User?.GetDisplayName();
                    book.CreatedOn = book.NowSystemTime;
                }
                List<BookStores.Entity.BookPictures> pictures = new List<Entity.BookPictures>();
                for (int i = 0; i < bookInfo.Book_Priture_List.Length; i++)
                {
                    BookStores.Entity.BookPictures picture = new Entity.BookPictures();
                    picture.ID = picture.NewKey;
                    picture.Book_ID = book.ID;
                    picture.Book_Picture_Order = i;
                    picture.Book_Picture_Url = bookInfo.Book_Priture_List[i];
                    pictures.Add(picture);
                }
                await m_IBookPicturesRepository.Insertable(pictures, unitOfWork).ExecuteCommandAsync();
                if (isEdit)
                {
                    isSuccess = await m_IBooksRepository.Updateable4Setting(book, unitOfWork).ExecuteCommandAsync() > 0;
                }
                else
                {
                    isSuccess = await m_IBooksRepository.Insertable(book, unitOfWork).ExecuteCommandAsync() > 0;
                }
                unitOfWork.Commit();
                return (isSuccess, guid);
            }
        }
        /// <summary>
        /// 根据参数查询数据
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<(List<DTO.Response.BookInfo>,int)> Query(BookQueryParam param)
        {
           var result =await  m_IBooksRepository.Query(param);
            List<DTO.Response.BookInfo> list = new List<DTO.Response.BookInfo>();
            if (result.Item2 > 0)
            {
                var languages =await m_IBookLanguageRepository.Queryable().ToListAsync();
                result.Item1.ForEach(async t =>
                {
                    var info = m_IMapper.Map<DTO.Response.BookInfo>(t);

                    var authors=await m_IBookAuthorsRepository.GetBookAuthorsByIds(info.Book_Author);
                    for (int i = 0; i < authors.Count; i++)
                    {
                        info.Book_Author[i] = $"{authors[i].Author_Name} [{authors[i].Nationality_CN}]";
                    }
                    List<string> langs = new List<string>();
                    for (int i = 0; i < info.Book_Language.Length; i++)
                    {
                        var lan = languages.Where(lt => lt.ID == info.Book_Language[i]).FirstOrDefault();
                        langs.Add($"{lan.Language}");
                    }
                    info.Book_Language = langs.ToArray();
                    list.Add(info);
                });
            }
            return (list, result.Item2);
        }
        /// <summary>
        /// 删除图书
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Delete(string id)
        {
            return await m_IBooksRepository.Updateable(new { ID = id, IsActive = "N", ModifyOn = DateTime.Now, ModifyBy = m_HttpContext.User?.GetDisplayName() }).ExecuteCommandAsync() > 0;
        }
    }
}